package com.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.entity.User;
import com.ticket.mapper.UserMapper;
import com.ticket.service.IUserService;
import com.ticket.utils.JwtUtils;
import com.ticket.vo.LoginVO;
import com.ticket.vo.RegisterVO;
import com.ticket.vo.PasswordUpdateVO;
import com.ticket.vo.UserProfileVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(LoginVO loginVO) {
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginVO.getUsername()));

        if (user == null || !passwordEncoder.matches(loginVO.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        return jwtUtils.generateToken(user);
    }

    @Override
    public void register(RegisterVO registerVO) {
        // 检查用户名是否已存在
        if (this.count(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, registerVO.getUsername())) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (this.count(new LambdaQueryWrapper<User>()
                .eq(User::getEmail, registerVO.getEmail())) > 0) {
            throw new RuntimeException("邮箱已被注册");
        }

        User user = new User();
        BeanUtils.copyProperties(registerVO, user);
        user.setPassword(passwordEncoder.encode(registerVO.getPassword()));
        user.setRole("USER");
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setAvatarUrl("default.jpg");
        this.save(user);
    }

    @Override
    @Transactional
    public void updateProfile(Long userId, UserProfileVO profile) {
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证邮箱是否被其他用户使用
        User existingUser = this.lambdaQuery()
            .eq(User::getEmail, profile.getEmail())
            .ne(User::getId, userId)
            .one();
        if (existingUser != null) {
            throw new RuntimeException("该邮箱已被使用");
        }

        user.setEmail(profile.getEmail());
        user.setPhone(profile.getPhone());
        
        this.updateById(user);
    }

    @Override
    @Transactional
    public void updateAvatar(Long userId, String avatarUrl) {
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setAvatarUrl(avatarUrl);
        this.updateById(user);
    }

    @Override
    @Transactional
    public void updatePassword(Long userId, PasswordUpdateVO passwordVO) {
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证原密码
        if (!passwordEncoder.matches(passwordVO.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }

        // 验证新密码
        if (!passwordVO.getNewPassword().equals(passwordVO.getConfirmPassword())) {
            throw new RuntimeException("两次输入的新密码不一致");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(passwordVO.getNewPassword()));
        this.updateById(user);
    }
}
